﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PageAdmin.Utils
{
    /// <summary>
    /// 字典帮助类
    /// </summary>
    public class DictionaryHelper
    {
        /// <summary>
        /// 是否包含键值，大小写忽略
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dictionary"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool ContainsKeyIgnoreCase<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key)
        {
            bool? keyExists;
            var keyString = key as string;
            if (keyString != null)
            {
                // Key is a string.
                // Using string.Equals to perform case insensitive comparison of the dictionary key.
                keyExists =
                    dictionary.Keys.OfType<string>()
                    .Any(k => string.Equals(k, keyString, StringComparison.InvariantCultureIgnoreCase));
            }
            else
            {
                // Key is any other type, use default comparison.
                keyExists = dictionary.ContainsKey(key);
            }
            return keyExists ?? false;
        }
    }
}